/**
 *  Eclipse Public License 1.0
 */
package org.fireblade.easysms;

import java.io.BufferedWriter;
import java.io.IOException;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import android.app.Service;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.util.Log;

/**
 * Action for getting the conversations overview html page
 */
public class HttpActionGetThreads {

  /**
   * own log tag
   */
  private static final String LOGTAG = MainActivity.EASY_SMS + HttpActionGetThreads.class.getSimpleName();


  /**
   * @param values
   * @param service the context/service
   * @param writer
   * @throws Exception
   */
  public static void process(Service service, Map<String, String> values, BufferedWriter writer)
    throws Exception {
    writer.write(Util.NEWLINE);
    writer
      .write("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\"\r\nhttp://www.w3.org/TR/html4/strict.dtd>\r\n<html><head>"
        + "<link rel=\"stylesheet\" href=\"/style.css\" type=\"text/css\" media=\"screen\" />"
        + "<META HTTP-EQUIV=\"content-type\" CONTENT=\"text/html; charset=utf-8\">");

    // SharedPreferences pref = service.getSharedPreferences(MainActivity.EASY_SMS_SP,
    // Context.MODE_PRIVATE);
    // int updateInterval = pref.getInt(MainActivity.UPDATE_INTERVAL, 0);
    // if (false && 0 != updateInterval) {
    // writer.write("<meta http-equiv=\"refresh\" content=\"" + updateInterval
    // + "; URL=/getthreads?autoupdate=true\">");
    // }

    writer
      .write("</head><body  bgcolor=\"#DDDDDD\">"
        + "<div id=\"r1\" style=\"position: fixed; top:0; right:0; height: 18px; width: 55px; background-color: #CCCCCC; text-align: right; \">"
        + "<small><a href=\"/getthreads?\">Update</a></small></div><table width=\"100%\">");
    writer.write(Util.NEWLINE);
    String id = values.get("id");
    if (null != id && !"".equals(id)) {
      String action = values.get("action");
      if (null != action) {
        if ("deleteThread".equals(action)) {
          Log.i(LOGTAG, "Delete thread " + id);
          MessageHelper.deleteThread(service, id);
        }
      }
    }
    boolean unreadMessages = writeThreads(service, writer);
    writer.write(Util.NEWLINE);
    writer.write("</table>");
    writer.write("</body></html>");
    writer.write(Util.NEWLINE);
  }


  /**
   * @param writer
   */
  private static boolean writeThreads(Service service, BufferedWriter writer) throws Exception {

    Set<Integer> threadIds = new HashSet<Integer>();

    Log.d(LOGTAG, "Got all thread ids: " + threadIds);

    // ADD DRAFT ONLY THREADS
    cursor = service.getContentResolver().query(uri,
      new String[] {  }, null, null, null);
    while (cursor.moveToNext()) {
      int threadId = cursor.getInt(0);
      if (threadIds.contains(threadId)) {
        Log.d(LOGTAG, "Thread " + threadId + " has a draft.");
        continue;
      } else {
        Log.d(LOGTAG, "Thread " + threadId + " is a draft only thread.");
      }
      Conversation thread = new Conversation();
      thread.threadId = threadId;
      thread.date = cursor.getLong(2);
      thread.body = cursor.getString(3);
      thread.count = 1;
      thread.type = 3;
      thread.unreadCount = 0;
      thread.uniqueContact = true;
      thread.isRead = true;

      if (null != canonicalId && !"".equals(canonicalId)) {
        uri2 = Uri.parse(uri);
        cursor2 = service.getContentResolver().query(uri2, null, null, null, null);
        if (cursor2.moveToNext()) {
          thread.address = cursor2.getString(0);
        }
        cursor2.close();
        String[] result = Util.getNameAndContactByNumber(thread.address, service);
        thread.contactId = Integer.parseInt(result[1]);
        thread.name = result[0];
      } else {
        thread.contactId = 0;
        thread.name = "?";
      }

      writeHTML(service, writer, thread);
      Log.d(LOGTAG, "Thread " + threadId + " finished.");
    }
    cursor.close();

    boolean unreadMessages = false;
    return unreadMessages;
  }


  /**
   * write the html code for one thread
   * @param service
   * @param writer
   * @param t
   * @throws IOException
   */
  public static void writeHTML(Service service, BufferedWriter writer, Conversation t) throws IOException {
    writer.write("<tr bgcolor=\"#EEEEEE\"><td width=\"3\"  "
      + (t.type != 1 && t.type != 2 && t.type != 3 && t.type != 6 ? "bgcolor=\"#FF0000\"" : (t.type == 3
        ? "bgcolor=\"#FFFF33\"" : (t.type == 6 ? "bgcolor=\"#0000FF\"" : (t.isRead ? "bgcolor=\"#EEEEEE\""
          : "bgcolor=\"#00CC00\"")))) + "    >" + /* t.type */""
      + "</td><td onClick=\"top.window.showthread.location.href='/showthread?id=" + t.threadId
      + (t.uniqueContact ? "" : "&different=true") + "'\" width=48>");
    if (t.contactId != 0) {
      writer.write("<img width=48 height=48 src=\"/getpicture?id=" + t.contactId + "\"/>");
    } else {
      writer.write("<img width=48 height=48 src=\"/getpicture?id=0\"/>");
    }
    writer.write("</td><td onClick=\"top.window.showthread.location.href='/showthread?id=" + t.threadId
      + (t.uniqueContact ? "" : "&different=true") + "'\"><table><tr><td><b>");
    if (t.name != null) {
      writer.write(t.name);
    } else {
      writer.write(t.address);
    }
    writer.write("</b>&nbsp;<b>[" + t.unreadCount + "/" + t.count + "]</b><br/>");
    writer.write("</td></tr><tr><td>");
    writer.write("<small>" + Util.format(service, t.date)
      + (t.name != null ? ("&nbsp;(" + t.address + ")") : "") + "</small>");
    writer.write("</td></tr><tr><td><small>");

    if (t.body.length() > 40) {
      t.body = t.body.substring(0, 36) + ("...");
    }
    t.body = t.body.replace("<", "&lt;");
    t.body = t.body.replace(">", "&gt;");
    t.body = t.body.replace("\r\n", " ");
    t.body = t.body.replace("\r", " ");
    t.body = t.body.replace("\n", " ");
    writer.write(t.body);
    writer.write("</small></td></tr></table></td>");
    writer.write("<td onClick=\"\" width=\"3\" bgcolor=\"#CCCCCC\"><a onClick=\"return confirm('"
      + service.getResources().getString(R.string.threads_del_thread) + "?')\" " + "href=\"/getthreads?id="
      + t.threadId + "&action=deleteThread\">D E L</a></td>");
    writer.write("</tr>");
    writer.write(Util.NEWLINE);
    writer.flush();
  }


  /**
   * load some details about an thread
   * @param threadId thread id
   * @param service the context/service
   * @return int[], pos 0 = total message count, pos 1 = "worst type" of a message
   *         (draft,queued,failed), pos 2 = unread count
   */
  public static int[] getDetails(Service service, int threadId) {
    Log.d(LOGTAG, "Get details.");
    int[] result = new int[4];
    //TODO
    Log.d(LOGTAG, "Details: " + result[0] + "/" + result[1] + "/" + result[2] + "/" + result[3]);
    return result;
  }
}